import requests
import json


def baidu_translate():
    # 百度翻译API的URL（通过分析网页获取）
    url = "https://fanyi.baidu.com/sug"

    # 设置请求头，进行UA伪装
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Origin': 'https://fanyi.baidu.com',
        'Referer': 'https://fanyi.baidu.com/'
    }

    while True:
        # 获取用户输入
        word = input("请输入要翻译的单词(输入q退出): ").strip()
        if word.lower() == 'q':
            print("退出翻译程序")
            break

        if not word:
            print("输入不能为空，请重新输入！")
            continue

        # 构造POST请求数据
        data = {
            'kw': word
        }

        try:
            # 发送POST请求
            response = requests.post(url, headers=headers, data=data)
            response.encoding = 'utf-8'  # 设置编码

            # 解析JSON响应
            result = json.loads(response.text)

            # 显示翻译结果
            if result.get('data'):
                print("翻译结果:")
                for item in result['data']:
                    print(f"{item['k']}: {item['v']}")
            else:
                print("未找到翻译结果")

        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {e}")
        except json.JSONDecodeError as e:
            print(f"解析响应数据错误: {e}")
        except Exception as e:
            print(f"发生未知错误: {e}")


if __name__ == "__main__":
    baidu_translate()